package com.heima.user.service.impl;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;

/**
 * APP用户信息表(ApUser)表服务实现类
 *
 * @author makejava
 * @since 2022-06-11 15:41:31
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    /**
     * 登陆
     *
     * @param loginDto:
     * @return ResponseResult
     * @author Administrator
     * @description TODO
     * @date 2022/6/11 19:43
     */
    @Override
    public ResponseResult login(LoginDto loginDto) {
        //1.判断是否为游客登陆
        if (StringUtils.isBlank(loginDto.getPhone()) && StringUtils.isBlank(loginDto.getPassword())) {
            String token = AppJwtUtil.getToken(0L);
            HashMap<String, String> map = new HashMap<>();
            map.put("token", token);
            return ResponseResult.okResult(map);
        }
        ApUser user = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, loginDto.getPhone()));
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }
        //用户输入的密码
        String password = loginDto.getPassword();
        //获取查询出的盐
        String salt = user.getSalt();
        //用户输入的密码加入盐之后
        String s = DigestUtils.md5DigestAsHex((password + salt).getBytes(StandardCharsets.UTF_8));
        if (!s.equals(user.getPassword())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        //获取令牌
        String token = AppJwtUtil.getToken(Long.parseLong(user.getId() + ""));
        user.setPassword("");
        user.setSalt("");
        HashMap map = new HashMap();
        map.put("user", user);
        map.put("token", token);
        return ResponseResult.okResult(map);
    }
}

